package com.alan.api.util;

import com.alan.server.bean.UserVO;
import com.alan.api.share.common.enums.ResponseCodeEnum;
import com.alan.api.share.dto.common.RequestBase;
import com.alan.api.share.dto.common.ResponseBase;
import com.alan.server.exception.ServiceException;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Alan on 2017/10/27.
 */
public class TokenUtils {

    private static RedisUtils redisUtils = null;

    public static String TOKEN = "token";


    public static String getTokenId(){
        return Mvc2Utils.getParameter(TOKEN);
    }

    /**
     * token校验
     * @param request
     * @param response
     * @return
     */
    public static ResponseBase checkToken(HttpServletRequest request,
                                          HttpServletResponse response) throws IOException{
        ResponseBase responseBase = new ResponseBase();
        responseBase.setEnum(ResponseCodeEnum.SUCCESS);
        String token = request.getParameter(TokenUtils.TOKEN);
//		token = "3dbeyfpnj0em8ayzfk3yunw051zfs3gk";
        if(StringUtils.isEmpty(token)){//token为空
            responseBase.setEnum(ResponseCodeEnum.INPUT_MUST_NOT_NULL);
            return responseBase;
        }
        token = token.trim();
        //TODO　test code
        if(token.equals("test")){
            return responseBase;
        }
        if (redisUtils == null){
            redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        }
        UserVO user = redisUtils.getObject(token, UserVO.class);
        if(user == null){
            responseBase.setEnum(ResponseCodeEnum.TOKEN_NOT_EXIST);
            return responseBase;
        }
        String uuid = redisUtils.get(user.getId().toString());
        if(StringUtils.isEmpty(uuid)){
            redisUtils.del(uuid);
            redisUtils.del(token);
            responseBase.setEnum(ResponseCodeEnum.TOKEN_IS_INVALID);
            return responseBase;
        }
        return responseBase;
    }

    public static void checkToken(RequestBase request) throws ServiceException {
        String token = request.getToken();
        if(StringUtils.isEmpty(token)){//token为空
            throw new ServiceException(ResponseCodeEnum.TOKEN_NOT_EXIST.getCode(),ResponseCodeEnum.TOKEN_NOT_EXIST.getMsg());
        }
        token = token.trim();
        if("intoken".equals(request.getToken())){
            return ;
        }
        if (redisUtils == null){
            redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        }
        UserVO user = redisUtils.getObject(token, UserVO.class);
        if(user == null){
            throw new ServiceException(ResponseCodeEnum.TOKEN_NOT_EXIST.getCode(),ResponseCodeEnum.TOKEN_NOT_EXIST.getMsg());
        }
        String uuid = redisUtils.get(user.getId().toString());
        if(StringUtils.isEmpty(uuid)){
            redisUtils.del(uuid);
            redisUtils.del(token);
            throw new ServiceException(ResponseCodeEnum.TOKEN_IS_INVALID.getCode(),ResponseCodeEnum.TOKEN_IS_INVALID.getMsg());
        }
        return ;
    }

    private static String getToken(UserVO userVO){
        if (redisUtils == null){
            redisUtils = SpringContextHolder.getBean(RedisUtils.class);
        }
        String uuid = RandomUtil.randomUUID();
        String token = redisUtils.get(userVO.getId().toString());
        if(StringUtils.isEmpty(token)){//token为空，未登录
            redisUtils.setObject(uuid, userVO, 60*30L);//30分钟,缓存用户信息
            redisUtils.set(userVO.getId().toString(), uuid, 60*30L);//30分钟，设备信息，用户挤下线
        }else{//已经登录
            UserVO beforeUser = redisUtils.getObject(token,UserVO.class);
            if(beforeUser == null){
                redisUtils.del(userVO.getId().toString());
                redisUtils.del(token);
                redisUtils.setObject(uuid, userVO, 60*30L);//30分钟,缓存用户信息
                redisUtils.set(userVO.getId().toString(), uuid, 60*30L);//30分钟，设备信息，用户挤下线
            }else{
                //TODO　可加用户挤下线功能
                redisUtils.del(userVO.getId().toString());
                redisUtils.del(token);
                redisUtils.setObject(uuid, userVO, 60*30L);//30分钟,缓存用户信息
                redisUtils.set(userVO.getId().toString(), uuid, 60*30L);//30分钟，设备信息，用户挤下线
            }
        }
        //token 没放在redis中有userVo中 通过 userId可能拿到
        userVO.setToken(uuid);
        return uuid;
    }


}
